package com.hsmw.api.service;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hsmw.api.config.jwt.CurrentHsmwUserUtils;
import com.hsmw.api.config.jwt.LoginUser;
import com.hsmw.api.controller.pub.TencentPushUtils;
import com.hsmw.api.mapper.HsmwAuditMapper;
import com.hsmw.api.mapper.HsmwComplainMapper;
import com.hsmw.api.mapper.HsmwReportRecordMapper;
import com.hsmw.api.vo.HomeVolume;
import com.hsmw.common.base.BasePage;
import com.hsmw.common.base.BaseService;
import com.htn.common.core.constant.CommonConstants;
import com.htn.common.core.constant.ComplainStatusEnum;
import com.htn.common.core.constant.PicTypeEnum;
import com.htn.common.core.utils.StringUtils;
import com.hsmw.domain.*;
import com.hsmw.domain.vo.DriverDetailVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class HsmwComplainService  extends BaseService<HsmwComplainMapper, HsmwComplain> {

    @Autowired
    private HsmwComplainMapper hsmwComplainMapper;

    @Autowired
    private CurrentHsmwUserUtils currentHsmwUserUtils;

    @Autowired
    private HsmwPictureService hsmwPictureService;

    @Autowired
    private HsmwReportRecordMapper hsmwReportRecordMapper;



    @Autowired
    private HsmwDriverUserService hsmwDriverUserService;



    /**
     * 列表查询
     * @param page
     * @param hsmwComplain
     * @return
     */
    public IPage<HsmwComplain> findComplainList(IPage page, HsmwComplain hsmwComplain) {

        LambdaQueryWrapper<HsmwComplain> lambdaQuery = Wrappers.lambdaQuery(HsmwComplain.class);
        if(StringUtils.isNotBlank(hsmwComplain.getComplainName())){
            lambdaQuery.eq(HsmwComplain::getComplainName,hsmwComplain.getComplainName());
        }
        if(StringUtils.isNotBlank(hsmwComplain.getComplainPhone())){
            lambdaQuery.eq(HsmwComplain::getComplainPhone,hsmwComplain.getComplainPhone());
        }
        if(StringUtils.isNotBlank(hsmwComplain.getComplainType())){
            String complainType = hsmwComplain.getComplainType();
            String[] arr = complainType.split(",");
            lambdaQuery.in(HsmwComplain::getComplainType,arr);
        }
        if(StringUtils.isNotBlank(hsmwComplain.getComplainStatus())){
            lambdaQuery.eq(HsmwComplain::getComplainStatus,hsmwComplain.getComplainStatus());
        }
        if(StringUtils.isNotBlank(hsmwComplain.getItemName())){
            lambdaQuery.eq(HsmwComplain::getItemName,hsmwComplain.getItemName());
        }
        if(StringUtils.isNotBlank(hsmwComplain.getCreateUser())){
            lambdaQuery.eq(HsmwComplain::getCreateUser,hsmwComplain.getCreateUser());
        }
        lambdaQuery.orderByDesc(HsmwComplain::getCreateTime);
        IPage<HsmwComplain> orderIPage = hsmwComplainMapper.selectPage(page, lambdaQuery);

        return orderIPage;
    }

    public void updateComplainStatus(HsmwComplain hsmwComplain) {


        LoginUser currentHsmwUser = currentHsmwUserUtils.getCurrentUserInfo();
        HsmwReportRecord hsmwReportRecord = hsmwComplain.getHsmwReportRecord();
        hsmwReportRecord.setReportId(hsmwComplain.getId());
        hsmwReportRecord.setReportStatus(hsmwComplain.getComplainStatus());
        //确认
        if (hsmwComplain.getComplainStatus().equals("1")) {
            hsmwReportRecord.setConfirmationTime(LocalDateTime.now());
            hsmwReportRecord.setConfirmationName(currentHsmwUser.getName());
            hsmwReportRecord.setConfirmationPhone(currentHsmwUser.getUsername());
        }
        // 解决
        if (hsmwComplain.getComplainStatus().equals("2")) {
            hsmwReportRecord.setReceiverName(currentHsmwUser.getName());
            hsmwReportRecord.setReceiverDeptName("测试部门");
            hsmwReportRecord.setReceiverPhone(currentHsmwUser.getUsername());
            hsmwReportRecord.setSolveTime(LocalDateTime.now());
        }
        // 回访
        if (hsmwComplain.getComplainStatus().equals("3")) {
            hsmwReportRecord.setVisitTime(LocalDateTime.now());
            String id = hsmwComplain.getId();
            HsmwComplain complain = hsmwComplainMapper.selectById(id);
            String msg = "您的投诉已被受理，请耐心等待平台的处理结果";
            TencentPushUtils.pushForeManMsg(msg,complain.getComplainPhone(),"has_new_message");
            TencentPushUtils.selfrunMsg(msg,complain.getComplainPhone(),"has_new_message");

        }
        //关闭
        if (hsmwComplain.getComplainStatus().equals("4")) {
            hsmwReportRecord.setCloseTime(LocalDateTime.now());
        }
        hsmwComplainMapper.updateById(hsmwComplain);
        hsmwReportRecordMapper.insert(hsmwReportRecord);

        if (CollectionUtil.isNotEmpty(hsmwComplain.getPicList())) {
            List<HsmwPicture> pictures = new ArrayList<>();
            List<HashMap> picList = hsmwComplain.getPicList();
            if (null != picList && picList.size() > 0) {
                for (HashMap<String, String> pic : picList) {
                    HsmwPicture temp = new HsmwPicture();
                    temp.setPicPath(pic.get("picPath"));
                    temp.setPicRealPath(pic.get("realPath"));
                    temp.setPortId(hsmwComplain.getId());
                    temp.setCreateTime(LocalDateTime.now());
                    temp.setPicType(PicTypeEnum.REPORT_IMAGER.getValue());
                    pictures.add(temp);
                }
            }
            hsmwPictureService.saveBatch(pictures);
        }
    }

    public List<HomeVolume> findCountOnWeek() {

        return hsmwComplainMapper.findCountOnWeek();
    }

    public List<HomeVolume> findCountOnMonth() {

        return hsmwComplainMapper.findCountOnMonth();
    }

    public List<HomeVolume> findCountOnYear() {
        return hsmwComplainMapper.findCountOnYear();
    }

    public HsmwComplain findComplainInfoById(String id) {

        HsmwComplain hsmwComplain = hsmwComplainMapper.selectById(id);
        Map map = new HashMap();
        List<HsmwPicture> list = hsmwPictureService.list(new LambdaQueryWrapper<HsmwPicture>().eq(HsmwPicture::getComplainId, id));
        if(CollectionUtil.isNotEmpty(list)){

            hsmwComplain.setHsmwPictures(list);
        }

        List<HsmwReportRecord> hsmwReportRecords = hsmwReportRecordMapper.selectList(new LambdaQueryWrapper<HsmwReportRecord>().eq(HsmwReportRecord::getReportId, id));
        hsmwComplain.setHsmwReportRecords(hsmwReportRecords);

        HashMap param  =new HashMap();
        String driverIds = hsmwComplain.getDriverIds();
        if(StringUtils.isNotBlank(driverIds)){
            param.put("driverIds",driverIds.split(","));
            List<DriverDetailVO> driverDetailVOS = hsmwDriverUserService.findDriverInfo(param);
            hsmwComplain.setDriverDetailVOS(driverDetailVOS);
        }
        return hsmwComplain;
    }



    /**
     * 项目端 列表查询
     * @return
     */
    public IPage<HsmwComplain> queryComplainList( BasePage<HsmwComplain> basePage) {
        IPage page = new Page(basePage.getPageNo(), basePage.getPageSize());
        LambdaQueryWrapper<HsmwComplain> lambdaQuery = Wrappers.lambdaQuery(HsmwComplain.class);
        LoginUser loginUser = currentHsmwUserUtils.getCurrentUserInfo();
        lambdaQuery.eq(HsmwComplain::getCreateUser,loginUser.getId());
        lambdaQuery.eq(HsmwComplain::getComplainType,CommonConstants.YES);
        // 根据
        if(StringUtils.isNotBlank(basePage.getQueryParam())){
            if(CommonConstants.NO.equals(basePage.getQueryParam())){
                lambdaQuery.in(HsmwComplain::getComplainStatus, ComplainStatusEnum.ONPROCESS.getValue());
            }else {
                lambdaQuery.in(HsmwComplain::getComplainStatus, ComplainStatusEnum.ENSURED.getValue());
            }
        }
        lambdaQuery.orderByDesc(HsmwComplain::getCreateTime);
        IPage<HsmwComplain> orderIPage = hsmwComplainMapper.selectPage(page, lambdaQuery);

        List<HsmwComplain> records= orderIPage.getRecords();
        if(CollectionUtil.isNotEmpty(records)){
            for(HsmwComplain  hsmwComplain :records){
                HashMap param  =new HashMap();
                String driverIds = hsmwComplain.getDriverIds();
                if(StringUtils.isNotBlank(driverIds)){
                    param.put("driverIds",driverIds.split(","));
                    List<DriverDetailVO> driverDetailVOS = hsmwDriverUserService.findDriverInfo(param);
                    hsmwComplain.setDriverDetailVOS(driverDetailVOS);
                }
                List<HsmwPicture> list = hsmwPictureService.list(new LambdaQueryWrapper<HsmwPicture>().eq(HsmwPicture::getComplainId, hsmwComplain.getId()));
                if(CollectionUtil.isNotEmpty(list)){
                    hsmwComplain.setHsmwPictures(list);
                }
                //如果是
                if(ComplainStatusEnum.ENSURED.getValue().equals(hsmwComplain.getComplainStatus()) || ComplainStatusEnum.CLOSED.getValue().equals(hsmwComplain.getComplainStatus())){
                    List<HsmwReportRecord> hsmwReportRecords = hsmwReportRecordMapper.selectList(
                            new LambdaQueryWrapper<HsmwReportRecord>().eq(HsmwReportRecord::getReportId, hsmwComplain.getId())
                                    .eq(HsmwReportRecord::getReportStatus,CommonConstants.YES));
                    if(CollectionUtil.isNotEmpty(hsmwReportRecords)){
                        HsmwReportRecord record = hsmwReportRecords.get(0);
                        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm");
                        hsmwComplain.setConfirmationTime(dtf2.format(record.getConfirmationTime()));
                        hsmwComplain.setConfirmationContent(record.getConfirmationContent());
                    }
                }
            }
            orderIPage.setRecords(records);
        }
        return orderIPage;
    }
}
